<template>
	<!-- <el-button type="primary" icon="el-icon-download" @click="int" style="margin-left:10px;">导入文章</el-button> -->
  <el-dialog
    v-loading.fullscreen="isLoading"
    v-model="modal1"
    element-loading-text="导入中..."
    title="导入文章"
    class="customdialog"
    :width="800"
	 :close-on-click-modal="false"
  >
    <el-row>
      <h2 align="center" class="mb20 f18" style='width: 100%;margin-bottom: 25px;'>请严格按照示例文件格式导入</h2>
    </el-row>
    <el-row>
      <p style="margin:5px 0 !important;color:#999;font-size:12px;">1.表格内橙色为必填，蓝色为选填</p>
    </el-row>
    <el-row>
      <p style="margin:5px 0 !important;color:#999;font-size:12px;">2.参考时长，单位是秒</p>
    </el-row>
    <el-row>
      <p style="margin:5px 0 !important;color:#999;font-size:12px;">3.回答次数限制，不填默认为0(无限制)</p>
    </el-row>
    <el-row style="margin-top:20px;display: flex;align-items: center;">
		<UploadExcel :loadingstatus='isLoading' :onSuccess="importHander" class="mt10"></UploadExcel>
		<el-button
			type="text"
			class="mr15"
			style='margin-left: auto;'
			@click="downloadHander(template)"
		>下载示例文件</el-button>
    </el-row>
    <template #footer>
      <el-button @click="modal1 = false">关闭</el-button>
    </template>
    <el-dialog v-model="modal2" title="导入失败列表" width="600px" append-to-body :close-on-click-modal="false">
      <el-table :data="error_list">
        <el-table-column align="left" label="所在行" prop="number">
          <template #scope="scope">
            <span style="font-size: 12px">第{{scope.row.number}}行</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="错误原因" prop="detail">
          <template #scope="scope">
            <span style="font-size: 12px">{{scope.row.detail}}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </el-dialog>
</template>
<script>
import UploadExcel from '@/components/scImportquest/upload'
import download from "downloadjs";
export default {
    name: "import",
    components: {
        UploadExcel,
        download
    },
    props: {
        courseId: {
            type: Number,
            default: ''
        }
    },
    data() {
        return {
            headers: {
                Authorization: this.$TOOL.data.get("A_TOKEN")
            },
            uploadUrl: process.env.VUE_APP_BASE_API + "admin/upload/create/excel",
            modal1: false,
            modal2: false,
            isLoading: false,
            template: "https://yypx-1318583591.cos.ap-chongqing.myqcloud.com/template/import_question.xlsx",
            error_list: []
        };
    },
    computed: {
        time() {
            return new Date().getTime();
        }
    },
    mounted() {
        
    },
    methods: {
        int() {
            this.modal1 = true;
			      this.isLoading = false
        },
        exports() {},
        async importHander(data) {
          this.isLoading = true
          await this._importHander(data, 0)
          if (this.error_list.length > 0) {
            this.modal1 = false;
            this.modal2 = true; 
          }
        },
        async _importHander(data, gloadIndex = 0) {
            this.isLoading = true;
            if (gloadIndex === 0) {
                this.error_list = [];
                if (!this.courseId) {
                    this.isLoading = false;
                    return false;
                }
            }

           
            let column = {
                标题: "title",
                难度系数: "difficultyRate",
                参考时长: "duration",
                回答次数限制: "answerLimit",
                文章内容: "content"
            };
            
            data.results.forEach(async (ele, index) => {
                if (gloadIndex === index) {
                    let _data = {};
                    for (let c in column) {
                       _data[column[c]] = ele[c] ? ele[c] : null;
                    }
                    
                    _data.courseId = this.courseId;
                    _data.status = 1;
                    _data.answerLimit = _data.answerLimit ? _data.answerLimit : 0;
                    if(this.error_list.length == 0){
                      this.$API.courseArticle.action.post(_data).then((res)=> {
                          if (res.error == 0) {
                            this._importHander(data, gloadIndex + 1);
                          }else {
                            this.error_list.push({
                              number: index + 2,
                              detail: res.message
                            });
                          }
                      }).finally(() => {})
                    }else {
                      this.isLoading = false;
                      this.error_list.push({
                          number: index + 2,
                          detail: res.message
                      });
                      this._importHander(data, gloadIndex + 1);
                    }  
                }
            });
            if (gloadIndex > data.results.length - 1) {
                this.isLoading = false;
                this.modal1 = false;
                if (this.error_list.length > 0) {
                    this.modal2 = true;
                } else {
                    this.modal2 = false;
                    this.$emit("success");
                    this.$notify.success("导入成功");
                }
            }
        },
        downloadHander(url) {
            let x = new XMLHttpRequest();
            x.open( "GET", url, true);
            x.responseType = "blob"
            x.onload = () => {
                download(x.response, '导入阅读文章模板.xlsx')
            };
            x.send();
        }
    }
};
</script>

<style scoped>
p {
  margin: 10px 0 !important;
}
</style>
